package com.module.circle.ui.circleDetails

import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.os.Bundle
import android.view.View
import android.view.animation.AccelerateDecelerateInterpolator
import android.view.animation.AccelerateInterpolator
import android.view.animation.DecelerateInterpolator
import android.widget.LinearLayout
import androidx.core.content.ContextCompat
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.common.app.base.AppPictureSelectionActivity
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.KeyPre
import com.common.app.data.bean.circle.CircleListModel
import com.common.app.data.bean.circle.CircleTaskModel
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.TimeUtils
import com.common.app.utls.TimeUtils.getTimeDateLong
import com.common.base.app.extras.doOnIOThread
import com.common.base.app.extras.doOnUiThread
import com.common.base.app.extras.formatDecimal
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.loadCircle
import com.common.base.app.extras.loadRound
import com.common.base.app.extras.no
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.startActivityResultLauncher
import com.common.base.app.extras.yes
import com.common.base.utils.AppUtils
import com.common.base.utils.JsonUtils
import com.common.base.utils.MathUtil
import com.common.base.utils.SpUtilsManagement
import com.common.base.utils.SpanUtils
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.UnitConversionUtils
import com.common.base.utils.ViewUtils
import com.common.base.widget.animator.CustomAnimation1
import com.common.base.widget.indicators.ColorFlipPagerTitleView
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.BasePopupView
import com.lxj.xpopup.enums.PopupAnimation
import com.module.ble.repo.UserStepsRelatedRecordRepo
import com.module.circle.R
import com.module.circle.databinding.CircleActivityCircleDetailsBinding
import com.module.circle.ui.changeIntroduction.ChangeMyIntroductionActivity
import com.module.circle.ui.circleMembersList.MembersListActivity
import com.module.circle.ui.createCircle.CreateCircleActivity
import com.module.circle.ui.taskManage.TaskManageActivity
import com.module.circle.ui.taskRanking.TaskRankingActivity
import com.scwang.smart.refresh.footer.ClassicsFooter
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import net.lucode.hackware.magicindicator.buildins.UIUtil
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.badge.BadgePagerTitleView


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/07/24
 * <p>
 * 描述：圈子详情页
 * <p>
 * 修订历史：
 */
class CircleDetailsActivity :
    AppPictureSelectionActivity<CircleActivityCircleDetailsBinding, CircleDetailsViewModel>(),
    View.OnClickListener {

    override fun getViewModel() = CircleDetailsViewModel::class.java
    override fun getViewContentBinding() =
        CircleActivityCircleDetailsBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_KEY)
    @JvmField
    var mBean: CircleListModel? = null

    @Autowired(name = KeyBundle.EXPAND_DATA)
    @JvmField
    var mValue: String? = null


    val titles = ArrayList<String>()
    private var currentSelectedIndex = 0  // 当前选中索引

    private val mAdapter by lazy { TaskRankingListItemAdapter() }

    var attachPopup: BasePopupView? = null

    var popAttachList = arrayOf<String>()
    var headTitleUtils: HeadTitleUtils? = null

    var circleTaskModel: CircleTaskModel?= null

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)
        headTitleUtils = HeadTitleUtils(this)
        headTitleUtils?.setTitle(resources.getString(R.string.circle_ac_circle_details_title))
        headTitleUtils?.setLineStyle(10)
        headTitleUtils?.setRightImg(
            ContextCompat.getDrawable(
                this,
                R.drawable.common_right_more_icon4
            )
        )

        headTitleUtils?.setRightActionCallBack(object : HeadTitleUtils.RightActionListener {
            override fun rightAction(v: View?) {
                if (attachPopup?.isShow == false) {
                    attachPopup?.show()
                }
            }

        })

        mViewContentBinding.tvSaveBtn.text =
            if ((ViewUtils.getString(R.string.circle_recommendation_circle_hint) == mValue)) getString(
                R.string.circle_add_circle_hint3
            ) else getString(R.string.circle_invite_members_hint)

        mAdapter.apply {
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = false
            mViewContentBinding.hrv.adapter = this
            setOnItemChildClickListener(object : OnItemChildClickListener {
                override fun onItemChildClick(
                    adapter: BaseQuickAdapter<*, *>,
                    view: View,
                    position: Int
                ) {
                    if (ViewUtils.isFastClick()) return //防止多次点击
                    val bundle = Bundle()
                    bundle.putParcelable(KeyBundle.BUNDLE_KEY, mAdapter.data[position])
//                    startActivity<CircleDetailsActivity>(bundle, false)
                }

            })
        }

        //上下拉刷新
        mViewContentBinding.pdView.setRefreshFooter(
            ClassicsFooter(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )
        mViewContentBinding.pdView.setEnableLoadMore(false)
        mViewContentBinding.pdView.setEnableLoadMoreWhenContentNotFull(false)
        getRefreshFooter()?.let { mViewContentBinding.pdView.setRefreshFooter(it) }
        mViewContentBinding.pdView.setRefreshHeader(
            ClassicsHeader(this).setAccentColor(
                ContextCompat.getColor(this, R.color.color_999999)
            )
        )

        titles.add(getString(R.string.circle_check_days_hint))
        titles.add(getString(R.string.circle_movement_distance_hint))
//        titles.add(getString(R.string.circle_running_pace_hint))

        initMagicIndicator()

        setVisibility(headTitleUtils?.getRightImg(), false)
    }

    override fun initEvents() {
        super.initEvents()

        mViewContentBinding.tvSaveBtn.setOnClickListener(onClick = this)
        mViewContentBinding.tvAllTaskRankingHint.setOnClickListener(onClick = this)
        mViewContentBinding.imgArrow.setOnClickListener(onClick = this)

        mViewContentBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                lazyInitData()
            }
        })

        LiveEventBus.get(KeyEvents.KEY_REFRESH_CIRCLE_DETAILS_EVENT).observe(this) {
            lazyInitData()
        }
    }

    override fun lazyInitData() {
        super.lazyInitData()

        setVisibility(
            mViewContentBinding.tvRightBtn,
            (ViewUtils.getString(R.string.circle_recommendation_circle_hint) != mValue)
        )

        with(mViewContentBinding.pBarMyProgress) {
            percent = MathUtil.div9((0..10).random().toString(), "10").toFloat()
            startAnimator(timeInterpolator = AccelerateDecelerateInterpolator(), duration = 600)
        }

        requestCirclesDetail()
        requestCirclesMembersList()
        getCirclesTask()

        // 更新当前选中索引
        currentSelectedIndex = 0
        // 先触发页面选择事件，再触发滚动事件
        mViewContentBinding.magicIndicator.onPageSelected(0)
        mViewContentBinding.magicIndicator.onPageScrolled(0, 0f, 0)
        getCirclesTaskRank()
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.tvSaveBtn -> {
                (ViewUtils.getString(R.string.circle_recommendation_circle_hint) == mValue).yes {
                    requestJoinCircles()
                }.otherwise {

                }

            }

            mViewContentBinding.imgArrow -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, mBean?.id ?: 0)
                bundle.putBoolean(KeyBundle.EXPAND_DATA, mBean?.is_leader?:false)
                startActivity<MembersListActivity>(bundle, false)
            }

            mViewContentBinding.tvAllTaskRankingHint -> {
                val bundle = Bundle()
                bundle.putInt(KeyBundle.BUNDLE_KEY, mBean?.id ?: 0)
                startActivity<TaskRankingActivity>(bundle, false)
            }
        }
    }


    private fun initMagicIndicator() {
        val commonNavigator = CommonNavigator(this)
        commonNavigator.adapter = object : CommonNavigatorAdapter() {
            override fun getCount(): Int {
                return titles.size
            }

            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
                val badgePagerTitleView: SimplePagerTitleView = ColorFlipPagerTitleView(context)
                badgePagerTitleView.text = titles[index]
                badgePagerTitleView.textSize = 14f
                badgePagerTitleView.normalColor = AppUtils.getColor(R.color.c_7f7f7f)
                badgePagerTitleView.selectedColor = AppUtils.getColor(R.color.product_color)
                badgePagerTitleView.setOnClickListener {
                    // 如果点击的是当前已选中的项，直接返回
                    if (currentSelectedIndex == index) return@setOnClickListener

                    // 更新当前选中索引
                    currentSelectedIndex = index

                    // 先触发页面选择事件，再触发滚动事件
                    mViewContentBinding.magicIndicator.onPageSelected(index)
                    mViewContentBinding.magicIndicator.onPageScrolled(index, 0f, 0)

//                    setHrvData()
                    getCirclesTaskRank(
                        when (currentSelectedIndex) {
                            1 -> "distance"
                            2 -> "pace"
                            else -> "days"
                        }
                    )
                }

                return badgePagerTitleView
            }

            override fun getIndicator(context: Context): IPagerIndicator {
                val indicator = LinePagerIndicator(context)
                indicator.mode = LinePagerIndicator.MODE_EXACTLY
                indicator.lineHeight = UIUtil.dip2px(context, 3.0).toFloat()
                indicator.lineWidth = UIUtil.dip2px(context, 24.0).toFloat()
                indicator.roundRadius = UIUtil.dip2px(context, 3.0).toFloat()
                indicator.setColors(AppUtils.getColor(R.color.product_color))
                indicator.startInterpolator = AccelerateInterpolator()
                indicator.endInterpolator = DecelerateInterpolator(2.0f)
                return indicator
            }
        }
        mViewContentBinding.magicIndicator.navigator = commonNavigator
        val titleContainer = commonNavigator.titleContainer
        titleContainer.showDividers = LinearLayout.SHOW_DIVIDER_NONE
        titleContainer.dividerPadding = ViewUtils.dp2px(15f).toInt()

        // 设置初始选中状态
        mViewContentBinding.magicIndicator.onPageSelected(currentSelectedIndex)
    }

    private fun finishPdView() {
        mViewContentBinding.pdView.finishRefresh()
        mViewContentBinding.pdView.finishLoadMore()
        mViewContentBinding.pdView.setNoMoreData(true)
    }

    private fun requestCirclesDetail() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.getCirclesDetail(mBean?.id ?: 0)
            .observe(this) {
                finishPdView()
                dismissLoadingDialog()
                it.isSuccess().yes {
                    it.isSuccess().yes {
                        it.Data?.let { dataIt ->
                            setVisibility(
                                mViewContentBinding.tvNote,
                                !dataIt.description.isNullOrEmpty()
                            )
                            setVisibility(mViewContentBinding.tvRightBtn, dataIt.is_leader)


                            if ((ViewUtils.getString(R.string.circle_my_circle_hint) == mValue)) {
                                setVisibility(headTitleUtils?.getRightImg(), true)

                                popAttachList = if (dataIt.is_leader) arrayOf(
                                    getString(R.string.circle_modif_circle_info_hint),
                                    getString(R.string.circle_member_manage_hint),
                                    getString(R.string.circle_task_manage_hint),
                                    getString(R.string.circle_disband_circle_hint),
                                ) else arrayOf(
                                    getString(R.string.circle_view_members_hint),
                                    getString(R.string.circle_quit_circle_hint)
                                )

                                if (attachPopup != null) attachPopup = null

                                attachPopup = XPopup.Builder(this)
                                    .atView(headTitleUtils?.getRightImg())
                                    .dismissOnTouchOutside(true)
                                    .isViewMode(true) //开启View实现
                                    .isRequestFocus(false) //不强制焦点
                                    .isTouchThrough(false)
                                    .hasShadowBg(false)
                                    .positionByWindowCenter(true)
                                    .popupAnimation(PopupAnimation.ScaleAlphaFromCenter)
                                    .asAttachList(
                                        popAttachList, null
                                    ) { position, text ->
                                        when (text) {
                                            getString(R.string.circle_modif_circle_info_hint) -> {
                                                if (mBean == null){
                                                    showErrorMsg()
                                                    return@asAttachList
                                                }
                                                val bundle = Bundle()
                                                bundle.putParcelable(KeyBundle.BUNDLE_KEY, mBean)
                                                startActivity<CreateCircleActivity>(bundle,false)
                                            }
                                            getString(R.string.circle_member_manage_hint) -> {
                                                val bundle = Bundle()
                                                bundle.putInt(KeyBundle.BUNDLE_KEY, mBean?.id ?: 0)
                                                bundle.putBoolean(KeyBundle.EXPAND_DATA, mBean?.is_leader?:false)
                                                startActivity<MembersListActivity>(bundle, false)
                                            }
                                            getString(R.string.circle_task_manage_hint) -> {
                                                val bundle = Bundle()
                                                bundle.putParcelable(KeyBundle.BUNDLE_KEY, circleTaskModel)
                                                bundle.putInt(KeyBundle.EXPAND_DATA, mBean?.id ?: 0)
                                                startActivity<TaskManageActivity>(bundle,false)
                                            }
                                            getString(R.string.circle_disband_circle_hint) -> requestDelCircles()
                                            getString(R.string.circle_view_members_hint) -> {
                                                val bundle = Bundle()
                                                bundle.putInt(KeyBundle.BUNDLE_KEY, mBean?.id ?: 0)
                                                bundle.putBoolean(KeyBundle.EXPAND_DATA, mBean?.is_leader?:false)
                                                startActivity<MembersListActivity>(bundle, false)
                                            }
                                            getString(R.string.circle_quit_circle_hint) -> requestExitCircles()
                                        }
                                    }
                            }


                            mViewContentBinding.picImg.loadRound(dataIt.image_url, 8)
                            mViewContentBinding.tvName.text = dataIt.name
//                        mViewContentBinding.tvRegion.text = dataIt.describe
                            mViewContentBinding.tvCreateTime.text = dataIt.created_at
                            mViewContentBinding.tvNote.text = dataIt.description
                            mViewContentBinding.tvMembersNum.text =
                                "${dataIt.member_count}${getString(R.string.circle_ren_splicing_hint)}${
                                    getString(R.string.circle_add_circle_hint2)
                                }"
                        }
                    }.otherwise {
                        showToast(it.Message)
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }
    }

    private fun requestCirclesMembersList() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.getCirclesMembersList(mBean?.id ?: 0) {
            finishPdView()
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    it.Data?.let { dataIt ->
                        // 设置头像URL列表
                        val avatarUrls = mutableListOf<String>()
                        dataIt.members?.let { membersIt ->
                            for ((index, element) in membersIt.withIndex()) {
                                (index == 0).yes {
                                    setVisibility(mViewContentBinding.imgCommanderHead, true)
                                    setVisibility(mViewContentBinding.tvCommanderMark, true)
                                    mViewContentBinding.imgCommanderHead.loadCircle(
                                        element.avatar_url
                                    )
                                }.otherwise {
                                    element.avatar_url.isNullOrEmpty().no {
                                        avatarUrls.add(element.avatar_url ?: "")
                                    }
                                }
                            }
                        }
//                            setVisibility(mViewContentBinding.multiAvatarView,avatarUrls.isNotEmpty())
                        mViewContentBinding.multiAvatarView.setAvatarUrls(avatarUrls)
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }


    private fun getCirclesTask() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        circleTaskModel= null
        showDialogLoading()
        mViewModel.getCirclesTask(mBean?.id ?: 0) {
            finishPdView()
        }.observe(this) {
            finishPdView()
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    setVisibility(mViewContentBinding.totalCircleTask, (it.Data?.taskinfo != null))

                    it.Data?.let { dataIt ->
                        dataIt.taskinfo?.let {taskinfoIt->
                            circleTaskModel = it.Data
                        }
                        mViewContentBinding.tvExerciseTime.text =
                            "${TimeUtils.getMonthDayMMdd(dataIt.taskinfo?.start_date?:0)}-${TimeUtils.getMonthDayMMdd(dataIt.taskinfo?.end_date?:0)}"
                        mViewContentBinding.tvCheckDays.text = "${dataIt.taskinfo?.days_req}"
                        mViewContentBinding.tvMileageForDays.text =
                            "${getString(R.string.common_exercise_hint)}${dataIt.taskinfo?.metric_value}${
                                getString(R.string.common_kilometers_splice)
                            }"

                            mViewContentBinding.tvTaskRemainingDays.text =
                            "${getString(R.string.common_remaining_unit)}${TimeUtils.formatTime((dataIt.taskinfo?.end_date?:0)-getTimeDateLong(), showHour = true)}"

                        getTheDayActivityData()
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun getCirclesTaskRank(type: String = "days") {
        mViewContentBinding.tvCompletionDaysHint.text =
            when (currentSelectedIndex) {
                1 -> getString(R.string.circle_completion_distance_hint)
//                2 -> "pace"
                else -> getString(R.string.circle_completion_days_hint)
            }
        mViewContentBinding.tvMyCompletionDaysHint.text =
            when (currentSelectedIndex) {
                1 -> getString(R.string.circle_completion_distance_hint)
//                2 -> "pace"
                else -> getString(R.string.circle_completion_days_hint)
            }
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.getCirclesTaskRank(mBean?.id ?: 0, type) {
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    it.Data?.let { dataIt ->
                        (dataIt.my_ranking == null).yes {
                            mViewContentBinding.tvRanking.setTextColor(getColor(R.color.text_content))
                            mViewContentBinding.tvRanking.text =
                                getString(R.string.common_rail_unit)
                            mViewContentBinding.tvRanking.setBackgroundResource(R.drawable.bg_round_f2f2f3_100)
                            mViewContentBinding.tvMyDays.text = getString(R.string.common_rail_unit)
                        }.otherwise {
                            dataIt.my_ranking?.let { myRankingIt ->
                                mViewContentBinding.tvRanking.text = myRankingIt.rank.toString()
                                mViewContentBinding.imgMyPic.loadRound(myRankingIt.avatar_url, 100)
                                mViewContentBinding.tvMyName.text = myRankingIt.user_name
                                mViewContentBinding.imgMySex.setImageDrawable(
                                    when (myRankingIt.sex) {
                                        0 -> getDrawable(R.drawable.circle_circle_sex_female_icon)
                                        1 -> getDrawable(R.drawable.circle_circle_sex_male_icon)
                                        else -> null
                                    }
                                )
//                            setVisibility(mViewContentBinding.tvMyCommanderMark, myRankingIt.badge_list)
                                mViewContentBinding.tvMyDays.text = myRankingIt.score.toString()

                                mViewContentBinding.tvRanking.setTextColor(
                                    when (myRankingIt.rank) {
                                        1 -> getColor(R.color.c_994000)
                                        2 -> getColor(R.color.c_4d6fb2)
                                        3 -> getColor(R.color.c_995d33)
                                        else -> getColor(R.color.text_content)
                                    }
                                )
                                mViewContentBinding.tvRanking.setBackgroundResource(
                                    when (myRankingIt.rank) {
                                        1 -> R.drawable.bg_round_ffcc33_100
                                        2 -> R.drawable.bg_round_c6d2ec_100
                                        3 -> R.drawable.bg_round_f0cdc2_100
                                        else -> R.drawable.bg_round_f2f2f3_100
                                    }
                                )
                            }
                        }

                        setVisibility(
                            mViewContentBinding.tvNotListHint,
                            dataIt.rankings.isNullOrEmpty()
                        )
                        mAdapter.setList(dataIt.rankings?.take(5))
                    }
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun requestDelCircles() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.requestDelCircles(mBean?.id ?: 0) {
            finishPdView()
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    LiveEventBus.get(KeyEvents.KEY_CREATE_CIRCLE_EVENT).post(this)
                    showToast(R.string.circle_del_circle_completed_hint)
                    finish()
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun requestExitCircles() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.requestExitCircles(mBean?.id ?: 0) {
            finishPdView()
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    LiveEventBus.get(KeyEvents.KEY_CREATE_CIRCLE_EVENT).post(this)
                    showToast(R.string.circle_exit_circle_completed_hint)
                    finish()
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }

    private fun requestJoinCircles() {
        if ((mBean?.id ?: 0) <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.requestJoinCircles(mBean?.id ?: 0) {
            finishPdView()
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    showToast(R.string.circle_join_circle_completed_hint)
                    lazyInitData()
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }


    /**
     * 获取当天活动信息
     */
    private fun getTheDayActivityData(){
        doOnIOThread {
            UserStepsRelatedRecordRepo.instance.findByOneDay(getTimeDateLong())?.let { originalListIt->
                if (originalListIt.isNullOrEmpty()) return@let
                val listItStr = JsonUtils.toJson(originalListIt)
                var totalDistance = 0.00//总距离
                originalListIt.sortedBy { it.createdTime }//按时间排序（升序）
                originalListIt.forEach { recordit->
                    totalDistance += recordit.distance
                }
                circleTaskModel?.taskinfo?.metric_value?.toDouble()
                val targetValue = circleTaskModel?.taskinfo?.metric_value?.toDouble() ?: 0.0
                val differenceValue = (targetValue-(totalDistance/1000).toInt()).toFloat()
                var myProgressObjectiveStr = (totalDistance/1000).toInt().toString()
                (SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0).yes {
                    myProgressObjectiveStr = "${UnitConversionUtils.convertLength((totalDistance/1000), UnitConversionUtils.LengthUnit.KM, UnitConversionUtils.LengthUnit.MI).formatDecimal(2)}${getString(R.string.common_feet_splice)}"
                }
                doOnUiThread {
                    mViewContentBinding.tvMyProgressObjective.text = "${getString(R.string.common_exercise_hint)}${myProgressObjectiveStr}${getString(R.string.common_kilometers_splice)}"
                    mViewContentBinding.tvMyProgressResultHint.text = "${if((SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0)) UnitConversionUtils.convertLength(circleTaskModel?.taskinfo?.metric_value?.toDouble()?:0.00, UnitConversionUtils.LengthUnit.KM, UnitConversionUtils.LengthUnit.MI).formatDecimal(2) else circleTaskModel?.taskinfo?.metric_value?.toInt()}${getString(R.string.common_kilometers_splice)}"
//                    mViewContentBinding.tvMyProgressResultHint.text = "${(totalDistance/1000).toInt()}${getString(R.string.common_kilometers_splice)}"
                    (differenceValue>=0).yes {
                        mViewContentBinding.tvMyProgressResult.text = "${getString(R.string.circle_still_short_today)}${if((SpUtilsManagement.getInt(KeyPre.KEY_METERING_UNIT_LENGTH,0) !=0)) UnitConversionUtils.convertLength(differenceValue.toDouble(), UnitConversionUtils.LengthUnit.KM, UnitConversionUtils.LengthUnit.MI).formatDecimal(1) else differenceValue.formatDecimal(1)}${getString(R.string.common_kilometers_splice)}"
                    }.otherwise {
                        mViewContentBinding.tvMyProgressResult.text = getString(R.string.circle_today_goal_been_achieved_today)
                    }

                    with(mViewContentBinding.pBarMyProgress) {
                        // 计算百分比：totalDistance占targetValue的百分比
                        percent = if (targetValue > 0) {
                            (((totalDistance/1000) / targetValue) * 100).toFloat()
                        } else {
                            0f
                        }
                        startAnimator(timeInterpolator = AccelerateDecelerateInterpolator(), duration = 600)
                    }
                }
            }
        }
    }
}